<!-- subpkg_consult/payment/index.vue -->
<script lang="ts" setup>
import { createInquiryOrderApi, getConsultOrderPreApi } from "@/apis/consult"
import { getPatientDetailApi } from "@/apis/patient"
import { orderPayApi } from "@/apis/pay"
import { useConsultStore } from "@/stores/consult"
import type { CustomPaymentInstance } from "@/types/components"
import type { OrderPreData } from "@/types/consult"
import type { PatientItem } from "@/types/patient"
import { ref } from "vue"

// 预下单信息
const orderPreInfo = ref<OrderPreData>()

const consultStore = useConsultStore()
// 获取预下单信息
const getOrderPreData = async () => {
  const res = await getConsultOrderPreApi({
    illnessType: consultStore.illnessType,
    type: consultStore.type, // 必传
  })
  orderPreInfo.value = res
}

// 调用 getOrderPreData 函数获取数据
getOrderPreData()

const paitentInfo = ref<PatientItem>()

// 获取患者详情
const getPaitentInfo = async () => {
  const res = await getPatientDetailApi(consultStore.patientId)
  paitentInfo.value = res
}

// 调用 getPaitentInfo 函数获取数据
getPaitentInfo()

// 提交表单 立即支付 创建订单 返回订单id
const onSubmit = async () => {
  const res = await createInquiryOrderApi({
    type: consultStore.type,
    illnessType: consultStore.illnessType,
    patientId: consultStore.patientId,
    depId: consultStore.depId,
    ...consultStore.illnessInfo,
  })
  // 保存订单id
  orderId.value = res.id
  // 打开支付组件
  paymentPopupRef.value?.open()
}

// 支付组件
const paymentPopupRef = ref<CustomPaymentInstance>()
// 订单id
const orderId = ref<string>("")

// 立即支付
const payNow = async (index: number) => {
  // 微信支付
  if (index === 0) {
    uni.showToast({
      title: "暂未开通微信支付",
      icon: "none",
    })
    return
  }
  // 加载loading
  uni.showLoading({
    title: "正在跳转支付宝...",
  })
  // 支付宝支付，参数发给后端，后端生成支付URL
  const res = await orderPayApi({
    orderId: orderId.value,
    paymentMethod: index.toString(),
    payCallback: "http://localhost:5173/#/subpkg_consult/room/index",
  })
  // 清除数据
  consultStore.clear()
  uni.hideLoading()
  // #ifdef H5
  location.href = res.payUrl // H5 端改变地址为支付 URL
  // #endif
}
// 关闭支付弹层
const closePayment = async () => {
  const res = await uni.showModal({
    title: "取消支付",
    content: "取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？",
    cancelText: "仍要关闭",
    cancelColor: "#848484",
    confirmText: "继续支付",
    confirmColor: "#16C2A3",
  })
  // 继续支付 无操作
  // 仍要关闭 -> 跳转首页
  if (res.cancel) {
    // 清除数据
    consultStore.clear()
    paymentPopupRef.value?.close()
    uni.reLaunch({ url: "/pages/my/index" })
  }
}
</script>

<template>
  <scroll-view v-if="orderPreInfo">
    <view class="payment-page">
      <uni-section
        title-font-size="32rpx"
        title-color="#121826"
        padding="30rpx"
        :title="`图文问诊 ${orderPreInfo.payment}元`"
      >
        <uni-list :border="false">
          <uni-list-item
            title="极速问诊"
            note="自动分配医生"
            thumb="/static/uploads/doctor-avatar.jpg"
            thumb-size="lg"
          />
          <uni-list-item
            title="优惠券"
            show-arrow
            :right-text="`-¥${orderPreInfo.couponDeduction}`"
          />
          <uni-list-item title="积分抵扣">
            <template #footer>
              <view class="uni-list-text-red"
                >-¥{{ orderPreInfo.pointDeduction }}</view
              >
            </template>
          </uni-list-item>
          <uni-list-item title="实付款">
            <template #footer>
              <view class="uni-list-text-red"
                >¥{{ orderPreInfo.actualPayment }}</view
              >
            </template>
          </uni-list-item>
        </uni-list>
      </uni-section>

      <view class="dividing-line"></view>

      <uni-section
        title-font-size="32rpx"
        title-color="#121826"
        padding="30rpx"
        title="患者资料"
      >
        <uni-list :border="false">
          <uni-list-item title="患者信息">
            <template #footer>
              <view class="uni-list-text-gray" v-if="paitentInfo">
                {{ paitentInfo.name }} | {{ paitentInfo.genderValue }} |
                {{ paitentInfo.age }}岁
              </view>
            </template>
          </uni-list-item>
          <uni-list-item
            border
            title="病情描述"
            :note="consultStore.illnessInfo.illnessDesc"
          />
        </uni-list>
      </uni-section>

      <!-- <view class="payment-agreement">
        <radio color="#20c6b2" value="1" />
        我已同意<text style="color: #20c6b2">支付协议</text>
      </view> -->
    </view>
    <!-- 下一步操作 -->
    <view class="next-step">
      <view class="total-amount">
        合计: <text class="number">¥{{ orderPreInfo.actualPayment }}</text>
      </view>
      <button class="uni-button" @click="onSubmit()">立即支付</button>
    </view>
    <!-- 全局支付组件 -->
    <custom-payment
      ref="paymentPopupRef"
      :order-id="orderId"
      :amount="orderPreInfo.actualPayment"
      @confirm="payNow"
      @close="closePayment"
    />
  </scroll-view>
</template>

<style lang="scss">
@import "./index.scss";
</style>
